<?php

namespace App\Commands;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

class TestCommand extends BaseCommand
{
    /**
     * The Command's Group
     *
     * @var string
     */
    protected $group = 'UserCommand';

    /**
     * The Command's Name
     *
     * @var string
     */
    protected $name = 'test';

    /**
     * The Command's Description
     *
     * @var string
     */
    protected $description = '';

    /**
     * The Command's Usage
     *
     * @var string
     */
    protected $usage = 'command:name [arguments] [options]';

    /**
     * The Command's Arguments
     *
     * @var array
     */
    protected $arguments = [];

    /**
     * The Command's Options
     *
     * @var array
     */
    protected $options = [
        '--reset' => '清空数据表后添加数据',
        '--max'   => '允许单次写入的最大值，最大允许值 200'
    ];

    /**
     * Actually execute a command.
     *
     * @param array $params
     */
    public function run(array $params)
    {
        $num  = 10;
        $max  = 100;
        $no   = 1;
        $page = 1;

        $db = db_connect();

        if (array_key_exists("reset", $params)) {
            $db->table("news")->truncate();
        }

        if (array_key_exists("max", $params) && intval($params["max"]) > 0) {
            $max = intval($params["max"]);
            $max = min($max, 200);
        }

        do {
            $res = file_get_contents("https://index-api.2345.com/informationflow/xxl/getNews?page={$page}&num={$num}&channel_id=1104&position=dh2023");
            $res = json_decode($res);

            $data = [];
            foreach ($res->data->list as $item) {
                $row = $db->table("news")->where("title", $item->title)->get(1)->getFirstRow();

                if ($row) continue;

                $data[] = [
                    "title"        => $item->title,
                    "summary"      => $item->sub_title,
                    "avatar"       => $item->img,
                    "url"          => $item->url,
                    "user_id"      => rand(1, 2),
                    "publish_time" => date('Y-m-d H:i', $item->publish_date / 1000),
                    "create_time"  => date('Y-m-d H:i', $item->publish_date / 1000),
                    "modify_time"  => date('Y-m-d H:i', $item->publish_date / 1000),
                ];

                CLI::write("{$no}. 标题: {$item->title}(URL: {$item->url})");
                CLI::newLine();
                $no++;

                if ($no > $max) break;
            }

            if (count($data)) {
                $db->table("news")->insertBatch($data);
            }

            $page++;
        } while (count($res->data->list) == $num && $no < $max);
    }
}
